<template>
  <div class="app-container">
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="postForm"
      label-position="right"
      label-width="100px"
      style="width: 400px; margin-left:50px;"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="postForm.roleName" clearable placeholder="角色名称" maxlength="20" />
      </el-form-item>
      <el-form-item label="角色编码" prop="roleCode">
        <el-input v-model="postForm.roleCode" placeholder="角色编码" maxlength="20" />
      </el-form-item>
      <el-form-item label="角色类型" prop="roleType">
        <el-radio v-model="postForm.roleType" label="0" border>管理员角色</el-radio>
        <el-radio v-model="postForm.roleType" label="1" border>普通角色</el-radio>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input
          v-model="postForm.roleDesc"
          :autosize="{ minRows: 2, maxRows: 4}"
          type="textarea"
          placeholder="角色描述"
          maxlength="200"
        />
      </el-form-item>
      <el-form-item label="权限">
        <el-tree
          ref="tree"
          :data="resourceData"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="defaultCheckedKeys"
          class="permission-tree"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="back()">返回</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addSysRole, updateSysRole, getSysRole } from '@/api/sys/role'
import { getSysResourceTree } from '@/api/sys/resource'

import msgUtil from '@/utils/msgUtil'
import routerUtil from '@/utils/routerUtil'

const defaultForm = {
  id: null,
  roleName: null,
  roleCode: null,
  roleDesc: null,
  roleType: 1,
  resourceIds: []
  // createdBy: getRealname(),
  // modifiedBy: getRealname()
}

// 处理返回的资源数据生成资源选择树
export function filterResourceTree(resources) {
  const res = []
  resources.forEach(resource => {
    const tmp = {}
    tmp.id = resource.id
    tmp.label = resource.resourceName
    if (resource.children) {
      tmp.children = filterResourceTree(resource.children)
    }
    // tmp.checked = true
    res.push(tmp)
  })
  return res
}

export default {
  name: 'SysRoleDetail',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      postForm: Object.assign({}, defaultForm),
      resourceData: [],
      systemOptions: [],
      oldRoleCode: null,
      resourceIds: null,
      authSystemId: null,
      defaultCheckedKeys: [], // 默认选中的功能
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        roleCode: [
          { required: true, message: '角色代码不能为空', trigger: 'blur' }
        ]
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  created() {
    if (this.isEdit) {
      // const id = this.$route.query && this.$route.query.id
      this.getSysRole(this.$route.query.id)
    } else {
      this.loading = false
      this.getResourceTree()
    }
  },
  methods: {
    async getResourceTree() {
      getSysResourceTree({}).then(response => {
        this.resourceData = filterResourceTree(response.data)
        console.log(this.resourceIds)
        if (this.resourceIds !== null) {
          this.defaultCheckedKeys = this.resourceIds.split('@')
        }
      })
    },
    // 修改角色
    updateSysRole() {
      this.postForm.resourceIds = this.$refs.tree.getCheckedKeys().join('@').concat('@').concat(this.$refs.tree.getHalfCheckedKeys().join('@'))
      updateSysRole(this.postForm).then(response => {
        msgUtil.success()
        routerUtil.backPath(this, '/sys/role/index')
      })
    },
    // 新增角色
    addSysRole() {
      this.postForm.resourceIds = this.$refs.tree.getCheckedKeys().join('@').concat('@').concat(this.$refs.tree.getHalfCheckedKeys().join('@'))
      addSysRole(this.postForm).then((response) => {
        msgUtil.success()
        routerUtil.backPath(this, '/sys/role/index')
      })
    },
    // 提交form
    submitForm() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            this.updateSysRole()
          } else {
            this.addSysRole()
          }
        }
      })
    }, // 返回上一个界面
    back() {
      routerUtil.backPath(this, '/sys/role/index')
    },
    // 获取角色信息并赋值给当前页面
    getSysRole(id) {
      var json = { 'id': id }
      getSysRole(json).then(response => {
        this.postForm = response.data
        this.resourceIds = response.data.resourceIds
        this.getResourceTree()
      })
    }
  }
}
</script>
<style scoped>

</style>
